<template>
	<view class="share-canvas">
		<canvas canvas-id="shareCanvas" :style="{width: `${width}px;height: ${height}px`}"></canvas>
	</view>
</template>

<script setup>
	import { getCurrentInstance, ref } from 'vue'
	const instance = getCurrentInstance()

	// data
	const width = ref(500)
	const height = ref(400)

	// methods
	const buildPreviewImage = ({
		nickname = '',
		post = '',
		companyName = '',
		phone = '',
		email = '',
		addr = '',
		photo = '',
	}) => {
		return new Promise((resolve, reject) => {
			try {
				const ctx = uni.createCanvasContext('shareCanvas', instance.proxy)

				// 填充画布
				ctx.setFillStyle('#eee')
				ctx.fillRect(0, 0, width.value, height.value)

				let y = 40

				// 绘制姓名
				ctx.font = 'bold 40px sans-serif'
				ctx.setFillStyle('#333')
				ctx.fillText(nickname, 100, y += 40)

				y += 20

				// 绘制岗位
				if (post) {
					ctx.font = 'normal 20px sans-serif'
					ctx.fillText(post, 40, y += 20 + 20)
				}

				if (companyName) {
					// 绘制企业
					ctx.setFontSize(20)
					ctx.fillText(companyName, 40, y += 20 + 20)
				}

				// 画横线
				ctx.beginPath()
				ctx.setLineWidth(1)
				ctx.setStrokeStyle('rgb(1, 82, 165)')
				ctx.moveTo(40, y + 20)
				ctx.lineTo(width.value - 40, y += 20)
				ctx.stroke()

				if (phone) {
					// 绘制电话
					ctx.setFontSize(20)
					ctx.fillText(phone, 40, y += 20 + 20)
				}

				// 绘制邮箱
				if (email) {
					ctx.setFontSize(20)
					ctx.fillText(email, 40, y += 20 + 20)
				}

				// 绘制地址
				if (addr) {
					ctx.setFontSize(20)
					ctx.fillText(addr, 40, y += 20 + 20)
				}

				// 绘制照片
				const imgW = 80
				const imgH = 100
				const w = 40
				const h = imgH * w / imgW
				ctx.drawImage('/static/logo.png', 40, 40, w, h)

				ctx.draw(false, (result) => {
					setTimeout(() => {
						uni.canvasToTempFilePath({
							canvasId: 'shareCanvas',
							success(res) {
								resolve(res.tempFilePath)
							},
							fail(e) {
								reject(e)
							}
						}, instance)
					}, 500)
				})
			} catch (e) { reject(e) }
		})
	}

	defineExpose({
		buildPreviewImage,
	})
</script>

<style lang="scss" scoped>
	.share-canvas {
		position: absolute;
		top: -10000px;
		z-index: -1000;
		opacity: 0;
	}
</style>